package com.andreamerla.petslife.fragment;

import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.TextView;
import com.andreamerla.petslife.R;
import com.andreamerla.petslife.activity.GpsActivity;
import com.andreamerla.petslife.activity.VetSearchActivity;
import com.andreamerla.petslife.manager.NavigationManager;
import com.andreamerla.petslife.model.Place;
import com.andreamerla.petslife.util.Utils;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import java.util.HashMap;

/**
 * Created by IntelliJ IDEA.
 * User: a.merla
 * Date: 22/07/13
 * Time: 17.34
 */
public class VetSearchMapFragment extends SupportMapFragment implements GoogleMap.InfoWindowAdapter, GoogleMap.OnInfoWindowClickListener {
    private static final float INITIAL_MAP_ZOOM_LEVEL = 8;

    private GoogleMap googleMap;
    private HashMap<Marker, Place> markerPlaceHashMap = new HashMap<Marker, Place>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);

        initMap();

        return view;
    }

    private void initMap() {
        // Controlla la presenza sul dispositivo di Google Play services APK
        if (!Utils.checkGooglePlayServices(getActivity()))
            return;

        setUpMapIfNeeded();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == Utils.GOOGLE_PLAY_SERVICES_REQUEST_CODE)
            if (resultCode == Activity.RESULT_OK)
                initMap();
    }

    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map
        if (googleMap == null) {
            googleMap = getMap();

            // Check if we were successful in obtaining the map
            if (googleMap != null) {
                // The Map is verified: it is now safe to manipulate the map
                googleMap.setMyLocationEnabled(true);

                googleMap.setInfoWindowAdapter(this);
                googleMap.setOnInfoWindowClickListener(this);

                // Update position and zoom map
                Location location = ((GpsActivity) getActivity()).gpsTracker.getLocation();
                if (location != null) {
                    LatLng position = new LatLng(location.getLatitude(), location.getLongitude());
                    if (googleMap != null)
                        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(position, INITIAL_MAP_ZOOM_LEVEL));
                }
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();

        addMarkers();
        if (markerPlaceHashMap.keySet().size() > 0)
            boundMarkers();
    }

    private void addMarkers() {
        if (googleMap == null)
            return;

        googleMap.clear();

        for (Place place : ((VetSearchActivity) getActivity()).getPlaceList()) {
            Marker marker = googleMap.addMarker(
                    new MarkerOptions()
                            .position(place.getLatLng())
                            .title(place.name)
                            .snippet(place.vicinity)
            );
            markerPlaceHashMap.put(marker, place);
        }
    }

    private void boundMarkers() {
        final LatLngBounds latLngBounds = Utils.getLatLngBounds(markerPlaceHashMap.keySet());
        final int padding = Math.round(Utils.convertDpToPixel(20, getActivity())); // Space (in px) to leave between the bounding box edges and the map edges

        try {
            googleMap.animateCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds, padding));
        } catch (IllegalStateException e) {
            // Layout not yet initialized
            final View mapView = getView();
            if (mapView.getViewTreeObserver().isAlive()) {
                mapView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    public void onGlobalLayout() {
                        mapView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                        googleMap.animateCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds, padding));
                    }
                });
            }
        }
    }

    public View getInfoWindow(Marker marker) {
        return null; // Use getInfoContents method to fill the info window
    }

    public View getInfoContents(Marker marker) {
        Place place = markerPlaceHashMap.get(marker);

        View view = getActivity().getLayoutInflater().inflate(R.layout.vet_map_info_window_layout, null);

        // Vet name
        TextView tvVetName = (TextView) view.findViewById(R.id.tv_vet_name);
        tvVetName.setText(place.name);

        // Vet address
        TextView tvVetAddress = (TextView) view.findViewById(R.id.tv_vet_address);
        tvVetAddress.setText(place.vicinity);

        // Vet description
        TextView tvVetDescription = (TextView) view.findViewById(R.id.tv_vet_description);
        tvVetDescription.setVisibility(View.GONE);
//        if (place.getDescription() != null)
//            tvVetDescription.setText(Html.fromHtml(place.getDescription()));

        return view;
    }

    public void onInfoWindowClick(Marker marker) {
        Place place = markerPlaceHashMap.get(marker);

        NavigationManager.startNavigationTo(getActivity(), place.geometry.location.lat, place.geometry.location.lng);
    }
}
